package com.example.myapplication2.dataBase;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.myapplication2.POJO.Shop.Good;
import com.example.myapplication2.POJO.Shop.ShoppingCart;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ShopHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "shop.db";
    private static final String Good_TABLE_NAME = "Good_info";
    private static final String ShoppingCart_TABLE_NAME = "Shopping_Cart";
    private static ShopHelper dbHelper = null;
    private static final int DB_VER = 1;
    private SQLiteDatabase sqLiteDatabaseRead = null;
    private SQLiteDatabase sqLiteDatabaseWrite = null;

    private ShopHelper(Context context) {
        super(context, DB_NAME, null, DB_VER);
    }

    //利用单例模式获取数据库帮助器的唯一实例
    public static ShopHelper getInstance(Context context) {
        if (dbHelper == null) {
            dbHelper = new ShopHelper(context);
        }
        return dbHelper;
    }

    public void openLink() {
        if (this.sqLiteDatabaseRead == null || !this.sqLiteDatabaseRead.isOpen()) {
            this.sqLiteDatabaseRead = this.dbHelper.getReadableDatabase();
        }
        if (this.sqLiteDatabaseWrite == null || !this.sqLiteDatabaseWrite.isOpen()) {
            this.sqLiteDatabaseWrite = this.dbHelper.getWritableDatabase();
        }
    }

    //打开数据库读连接
    public SQLiteDatabase openReadLink() {
        if (sqLiteDatabaseRead == null || !sqLiteDatabaseRead.isOpen()) {
            sqLiteDatabaseRead = dbHelper.getReadableDatabase();
        }
        return sqLiteDatabaseRead;
    }

    //打开数据库写连接
    public SQLiteDatabase openWriteLink() {
        if (sqLiteDatabaseWrite == null || !sqLiteDatabaseWrite.isOpen()) {
            sqLiteDatabaseWrite = dbHelper.getWritableDatabase();
        }
        return sqLiteDatabaseWrite;
    }

    //关闭连接
    public void closeLink() {
        if (sqLiteDatabaseWrite != null || sqLiteDatabaseWrite.isOpen()) {
            //关闭然后置空节约内存
            sqLiteDatabaseWrite.close();
            sqLiteDatabaseWrite = null;
        }
        if (sqLiteDatabaseRead != null || sqLiteDatabaseRead.isOpen()) {
            //关闭然后置空节约内存
            sqLiteDatabaseRead.close();
            sqLiteDatabaseRead = null;
        }
    }

    //创建
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        String car = "CREATE TABLE IF NOT EXISTS " + ShoppingCart_TABLE_NAME + " (" +
                " _id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
                "good_name VARCHAR NOT NULL," +
                "introduce VARCHAR NOT NULL," +
                "img VARCHAR NOT NULL," +
                "good_id INTEGER NOT NULL," +
                "total_Price INTEGER NOT NULL," +
                "count INTEGER NOT NULL," +
                "price INTEGER NOT NULL" +
                ");";
        sqLiteDatabase.execSQL(car);

        String good = "CREATE TABLE IF NOT EXISTS " + Good_TABLE_NAME + " (" +
                " _id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
                "good_name VARCHAR NOT NULL," +
                "introduce VARCHAR NOT NULL," +
                "img VARCHAR NOT NULL," +
                "price INTEGER NOT NULL" +
                ");";
        sqLiteDatabase.execSQL(good);
        //初始化数据库内容
    }

    //更新数据表结构,仅仅是版本不一致的时候,Version must be >= 1, was 0
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {

    }

    //查询所有商品
    public List<Good> GoodAll() {
        List<Good> list = new ArrayList<>();
        System.out.println("开始执行查询");
        Cursor query = sqLiteDatabaseRead.query(Good_TABLE_NAME, null, null, null, null, null, null);
        System.out.println("查询完毕....");
        int count = query.getCount();
        if (count > 0) {
            while (query.moveToNext()) {
                Good good = new Good();
                good.setId(query.getLong(0));
                good.setGoodName(query.getString(1));
                good.setIntroduce(query.getString(2));
                good.setImg(query.getString(3));
                good.setPrice(query.getLong(4));
                list.add(good);
            }
            query.close();
        }
        return list;
    }

    //查询购物车内所有商品
    public List<ShoppingCart> ShoppingCartList() {
        List<ShoppingCart> list = new ArrayList<>();
        Cursor query = sqLiteDatabaseRead.query(ShoppingCart_TABLE_NAME, null, null, null, null, null, null);
        if (query.getCount() > 0) {
            while (query.moveToNext()) {
                ShoppingCart shoppingCart = new ShoppingCart();
                shoppingCart.setId(query.getLong(0));
                shoppingCart.setGoodName(query.getString(1));
                shoppingCart.setIntroduce(query.getString(2));
                shoppingCart.setImg(query.getString(3));
                shoppingCart.setGoodId(query.getLong(4));
                shoppingCart.setTotalPrice(query.getLong(5));
                shoppingCart.setCount(query.getLong(6));
                shoppingCart.setPrice(query.getLong(7));
                list.add(shoppingCart);
            }
        }
        query.close();
        return list;
    }

    //删除购物车内某个商品
    public boolean deleteByGoodId(Long id) {
        sqLiteDatabaseWrite.delete(ShoppingCart_TABLE_NAME, "_id=?", new String[]{id.toString()});
        return true;
    }


    //计算购物车里面的数量
    public Long Count() {
        Long count = 0L;
        Cursor query = sqLiteDatabaseRead.query(ShoppingCart_TABLE_NAME,new String[]{"count"},null,null,null,null,null );
        int queryCount = query.getCount();
        if (queryCount>0){
            while (query.moveToNext()){
                long queryLong = query.getLong(0);
                count=count+queryLong;
            }
        }
        return count;
    }

    //清空购物车
    public boolean empty() {
        sqLiteDatabaseWrite.delete(ShoppingCart_TABLE_NAME, "1=1", null);
        return true;
    }

    public void addGood(Good good) {
        ContentValues values = new ContentValues();
        values.put("good_name", good.getGoodName());
        values.put("introduce", good.getIntroduce());
        values.put("img", good.getImg());
        values.put("price", good.getPrice());
        long insert = -1;
        //第一个参数是表的名称
        //第二个参数为空值字段，就是如果第三个参数为空（null)的时候就会用到第二个参数的值。用第二个参数代替第三个参数组拼成SQL语句
        //比如：insert into person(name) values(null)   这里的person字段使用了第二个参数的name
        //第三个参数不为空就不会用到第二个参数
        insert = sqLiteDatabaseWrite.insert(Good_TABLE_NAME, null, values);
    }

    public void addToCar(Good good) {
        Long id = good.getId();
        Cursor query = sqLiteDatabaseRead.query(ShoppingCart_TABLE_NAME, null, "good_id=?", new String[]{id + ""}, null, null, null);
        ShoppingCart shoppingCart = new ShoppingCart();
        Long price = good.getPrice();
        shoppingCart.setGoodId(good.getId());
        shoppingCart.setImg(good.getImg());
        shoppingCart.setIntroduce(good.getIntroduce());
        shoppingCart.setPrice(price);

        //判定查询为空否
        if (query.getCount() > 0) {
            //移动游标到第一条
            query.moveToFirst();
            shoppingCart.setId(query.getLong(0));
            long count = query.getLong(6);
            count = count + 1;
            long total_Price = count * price;
            //更新操作
            ContentValues values = new ContentValues();
            values.put("count", count);
            values.put("total_Price", total_Price);
            sqLiteDatabaseWrite.update(ShoppingCart_TABLE_NAME, values, "good_id=?", new String[]{good.getId().toString()});
        } else {
            //新增操作
            ContentValues values = new ContentValues();
            values.put("count", 1);
            values.put("price", good.getPrice());
            values.put("total_Price", good.getPrice());
            values.put("good_name", good.getGoodName());
            values.put("introduce", good.getIntroduce());
            values.put("img", good.getImg());
            values.put("good_id", good.getId());
            sqLiteDatabaseWrite.insert(ShoppingCart_TABLE_NAME, null, values);
        }
        query.close();
    }
}
